﻿using System;
using System.Collections;
using System.Windows.Forms;

namespace FileListView
{
    class ListViewSort : IComparer
    {

        // Property to get/set the column to use for comparison. 
        public int Column
        {
            get; 
            set;
        }

        // Property to get/set whether numeric comparison is required 
        // as opposed to the standard alphabetic comparison. 
        public bool Numeric
        {
            get; 
            set;
        }

        public ListViewSort(int columnIndex)
        {
            Column = columnIndex;
        }

        public int Compare(object x, object y)
        {
            // Convert the arguments to ListViewItem objects. 
            var itemX = x as ListViewItem;
            var itemY = y as ListViewItem;

            // Handle logic for null reference as dictated by the  
            // IComparer interface. Null is considered less than 
            // any other value. 
            if (itemX == null && itemY == null) return 0;
            else if (itemX == null) return -1;
            else if (itemY == null) return 1;

            // Shortcircuit condition where the items are references 
            // to the same object. 
            if (itemX == itemY) return 0;

            // Determine if numeric comparison is required. 
            if (Numeric)
            {
                // Convert column text to numbers before comparing. 
                // If the conversion fails, just use the value 0. 
                decimal itemXVal, itemYVal;

                if (!Decimal.TryParse(itemX.SubItems[Column].Text, out itemXVal))
                {
                    itemXVal = 0;
                }
                if (!Decimal.TryParse(itemY.SubItems[Column].Text, out itemYVal))
                {
                    itemYVal = 0;
                }

                return Decimal.Compare(itemXVal, itemYVal);
            }
            else
            {
                // Keep the column text in its native string format 
                // and perform an alphabetic comparison. 
                var itemXText = itemX.SubItems[Column].Text;
                var itemYText = itemY.SubItems[Column].Text;

                return String.Compare(itemXText, itemYText);
            }
        }

    }
}
